package com.mty.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Teacher马（2508531326@qq.com）
 * @date ：Created in 2022/11/2 16:59
 * @description：
 * @modified By：
 * @version:
 */
public class JWTUtil {
        private static String sign="mty-aaa";
        //1.生成jwt的token方法
        public static String createJWT(Map<String,Object> map){
            //定义头信息
            Map<String,Object> head= new HashMap<>();
            head.put("alg","HS256");
            head.put("typ","JWT");
            //定义颁发时间
            Date iat=new Date();
            //过期时间
            Calendar expire = Calendar.getInstance();
            expire.set(Calendar.SECOND,7200);
            Date expireTime = expire.getTime();

            String token = JWT.create()
                    //头信息
                    .withHeader(head)
                    //设置颁发时间
                    .withIssuedAt(iat)
                    //设置过期时间
                    .withExpiresAt(expireTime)
                    //自定义的内容
                    .withClaim("loginInfo",map)
                    //签名
                    .sign(Algorithm.HMAC256(sign));
            return token;
        }

        //2.校验token是否有效
        public static boolean verifyToken(String token){
            //获取一个JWT校验对象
            JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
            try {
                //调用校验功能
                DecodedJWT verify = build.verify(token);
                return true;
            }catch (Exception e){
                System.out.println("token无效");
                return false;
            }

        }

        //3.从token中获取相关的载荷内容
        public static Map<String,Object> getTokenChaim(String token){
            //获取一个JWT校验对象
            JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
            //调用校验功能
            DecodedJWT verify = build.verify(token);
            Claim loginInfo = verify.getClaim("loginInfo");
            return loginInfo.asMap();
        }

        public static void main(String[] args) {
            Map<String,Object> map=new HashMap<>();
            map.put("username","张三");
            map.put("sex","男");
            String jwt = createJWT(map);
            System.out.println(jwt);

            Map<String, Object> tokenChaim = getTokenChaim("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbkluZm8iOnsic2V4Ijoi55S3IiwidXNlcm5hbWUiOiLlvKDkuIkifSwiZXhwIjoxNjY3MzgzNTYwLCJpYXQiOjE2NjczNzYzNzJ9.HPknEAU2I4PfmLAttY0YsEAVyS77Dzxpd8YH1BKSKgk");
            System.out.println(tokenChaim);

        }
    }


